<?php

namespace app\model;

use app\exception\ApiException;
use app\extensions\lib\push\Push;
use Illuminate\Database\QueryException;
use support\Log;
use support\Model;

class TokenInfo extends Model
{
    protected $table = 'token_infos';
    protected $primaryKey = 'id';
    public $timestamps = false;
    public static $update_redis_queue_key = 'queue_token_infos';
    const TOKEN_LIMIT = 10000;
    protected $fillable = ['cate_id','game_id','package_id','channel_id','os_id','udid','token','ip','updated_at'];


    /**
     * 搜索当前的 udid,token 信息列表
     * @param $data
     * @param int $page
     * @param int $limit
     * @param array $only_token :token没有索引，直接传组装性能好（不用查询
     * @param string $token_os_id 这批token的os_id
     * @param bool $is_return_sum
     * @return array
     */
    public function getUserList($data,$page=1,$limit=0,$only_token=[],$token_os_id = '',$is_return_sum=false){
        $TokenInfo = new TokenInfo();
        //可以搜索的字段
        $searchColumns = ['cate_id','game_id','package_id','channel_id','os_id','udid','token'];
        /*$game_id = $data['game_id'] ?? 0;
        if($game_id){
            $role_id = $data['role_id'] ?? '';
            $server_id = $data['server_id'] ?? '';
            $cate_id = 0;
            $game_id && $cate_id = (new Game())->where('id',$game_id)->value('cate_id');
            if($role_id || $server_id){
                $raw = [];
                $role_id && $raw[] = "(role_id = '{$role_id}')";
                $server_id && $raw[] = "(server_id = '{$server_id}')";
                $udids = Db::connection('mysql_data')->table('roles_'.$cate_id)
                    ->whereRaw(implode(' and ',$raw))->orderBy('id','desc')->pluck('udid');
                $udids && $udids = implode(',',$udids);
            }
        }
        if(isset($udids) && $udids){
            $data['udid'] .= ','.$udids;
        }*/

        $test = [];

        $build = $TokenInfo;
        foreach ($searchColumns as $column){
            if(isset($data[$column]) && $data[$column]){

                if(in_array($column,['udid','token','package_id','game_id'])){
                    if(is_string($data[$column])){
                        $values = array_filter(explode(',',$data[$column]));
                    } else{
                        $values = $data[$column];
                        !is_array($values) && $values = [$values];
                    }
                }else{
                    $values = [$data[$column]];//暂支持单个;
                }
                $build = $build->wherein($column,$values);
                $test[$column] = $values;
            }
        }
        if($is_return_sum){
            return $build->count();
        }
        //最大id限制，防止异步进行中有数据插入而影响的预计用户数量
        if(isset($data['max_id']) && $data['max_id']){
            $build = $build->where('id','<=',$data['max_id']);
        }
        $gpBuild  = clone $build;
        $package_ids = $gpBuild->groupBy('package_id')->pluck('package_id')->toArray();


        $column = ['token','package_id'];
        $list = [1=>[],2 =>[],3=>[]];

        $limit = $limit ?:self::TOKEN_LIMIT;
        foreach ($package_ids as $package_id){
            $buildList = [
                1 => clone $build,
                2 => clone $build,
                3 => clone $build,
            ];
            foreach ($list as $os_id =>$empty){
                $tmpBuild = $buildList[$os_id];
                if($only_token){
                    if ($token_os_id && $token_os_id != $os_id) continue;//表明这批token属于 os_id类型
                    $list[$os_id][$package_id] = ['package_id'=>$package_id,'tokens'=>implode(',',$only_token),'page'=>$page,'limit'=>$limit];
                    continue;
                }

                if($tmpBuild){
                    $ttmpBuild = $tmpBuild->where('package_id',$package_id)->where('os_id',$os_id);
                    $count = $ttmpBuild->count();
                    if($count){
                        $offset = ($page-1) * $limit;
                        try{
                            $tokenList  = $ttmpBuild->orderBy('created_at','asc')->offset($offset)->limit($limit)->select('token','udid')->get()->toArray();
                        }catch (QueryException $exception){
                            Log::channel('sql')->error("offset:{$offset}-limit:{$limit}".json_encode($test));
                            $tokenList = [];
                        }

                        if($tokenList){
                            $tokens = array_column($tokenList,'token');
                            $udids = array_column($tokenList,'udid');
                            $list[$os_id][$package_id] = ['package_id'=>$package_id,'tokens'=>implode(',',$tokens),'udids'=>implode(',',$udids),'page'=>$page,'limit'=>$limit];
                        }
                    }
                }

            }
        }

        //group_concat 长度限制
        //$list = $build->where('os_id',1)->groupBy('package_id')->select('package_id',Db::raw('group_concat(token) tokens'))->get()->toArray();
        //$list2 = $build2->where('os_id',2)->groupBy('package_id')->select('package_id',Db::raw('group_concat(token) tokens'))->get()->toArray();
        return $list;
    }

    public function getBatchUserList($data){
        $push_data_public = $data['push_data_public'] ?? '';
        !is_array($push_data_public) && $push_data_public = json_decode($push_data_public,true) ?: [];
        $version = $data['version'] ?? '';
        $push_payloads = $data['push_payloads'] ?? '';
        !is_array($push_payloads) && $push_payloads = json_decode($push_payloads,true) ?: [];

        //最外层的用户条件
        $publicUserData = $data;
        unset($publicUserData['push_data_public'],$publicUserData['push_payloads']);
        unset($publicUserData['is_finish'],$publicUserData['is_add']);
        $userData = [];
        $message = [];
        $messageColumns = ['notification','custom_data'];

        if($push_payloads){
            foreach ($push_payloads as $payload){
                if(!is_array($payload)) throw new ApiException('push_payloads param error');
                $push_data = $payload['push_data'] ?? '';
                !is_array($push_data) && $push_data = json_decode($push_data,true) ?: [];
                $diyUserData = $payload;
                if(isset($diyUserData['push_data'])) unset($diyUserData['push_data']);
                $userData[] = array_merge($publicUserData,$diyUserData);
                $message[] = array_merge($push_data_public,$push_data,compact('version'));
            }
        }else{
            $userData[] = $publicUserData;
            $message[] = array_merge($push_data_public,compact('version'));
        }

        if(count($message)>10){
            throw new ApiException('push_payloads  max 100');
        }

        return compact('message','userData');
    }

    public function refreshInvalid($tokens=[]){
        if(env('APP_ENV')!='production') return;
        if($tokens){
            $this->wherein('token',$tokens)->delete();
        }else{
            //google 两个月
            $time = date('Y-m-d H:i:s',time() - 86400 * 60);
            $this->where('os_id',1)->where('updated_at','<',$time)->delete();
        }

    }


    public function getInsideUserList($data){

    }

}